<?php
namespace Admin\Controller;

//图片上传类
class PicUploadController extends \Think\Controller {

    public $pro_path;//项目所在目录的绝对路径

    public function _initialize() {
        header("Content-Type: text/html; charset=utf-8");
        $this->pro_path = str_replace('ThinkPHP/', '', THINK_PATH);
    }
    
    public function index() {
        $res = $this->uploadImg();
        if ($res['status'] == 1 && $_REQUEST['width'] && $_REQUEST['height']) {//缩略裁剪
            $this->thumb($res['path'], $_REQUEST['width'], $_REQUEST['height']);
        }
        echo json_encode($res);die;
    }
    
    //上传微信素材
    public function material() {
        $res = $this->uploadImg();

        if ($res['status'] == 1) {
            try {
                //请求微信接口
                $media  = new \Overtrue\Wechat\Media(C('APPID'), C('APPSECRET'));
                $result = $media->forever()->image($res['path']);
                $res['media_id'] = $result['media_id'];
                $res['url']      = $result['url'];
            } catch (\Exception $e) {
                $res = array('status'=>0, 'info'=>$e->getMessage());
            }
        }
        
        echo json_encode($res);die;
    }

    //上传图片
    public function uploadImg() {
        $upload           = new \Think\Upload();
        $upload->maxSize  = 10145728;  
        $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');
        $upload->rootPath = $this->pro_path.'storage/Upload/';
        $upload->savePath = 'admin/';
        $file             = array_values($_FILES);
        $info             = $upload->uploadOne($file[0]);

        if(!$info){
            return array('status' => 0, 'info' => $upload->getError());
        }else{
            return array('status' => 1, 'info' => $info['savepath'].$info['savename'], 'path' => $upload->rootPath.$info['savepath'].$info['savename']);
        }
    }
	
    //生成做略图
	public function thumb($img, $width = 900, $height = 900) {
		$image = new \Think\Image();
        $image->open($img);
        $size = $image->size();
        //if($size[0] <= $width && $size[1] <= $height) return;
        $image->thumb($width, $height,\Think\Image::IMAGE_THUMB_CENTER)->save($img);
    }

    //测试
    public function test() {
        echo '<html><body>
        <form action="'.U('Admin/PicUpload/material').'" method="post" enctype="multipart/form-data">
            宽<input type="text" name="width" />
            高<input type="text" name="height" />
            <input type="file" name="pic" />
            <input type="submit" />
        </form></body></html>';
    }

}